package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.view.ActionSheetDialog;
import com.android.uu.view.ActionSheetDialog.OnSheetItemClickListener;
import com.android.uu.view.ActionSheetDialog.SheetItemColor;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.AddImageAdapter;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageGridView;
import com.hemaapp.yjnh.view.YjnhImageWay;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.image.load.XtomImageTask;
import xtom.frame.util.XtomFileUtil;
import xtom.frame.util.XtomImageUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 田主发布定制农作物的成长日志
 *
 * @author GuiyouZhang
 *         创建时间：2015年9月21日 上午11:10:38
 *         最后修改时间：上午11:10:38
 */
public class ReleaseJournalActivity extends BaseActivity implements OnClickListener {

    private final static int REQUEST_CAMERA = 0x01;
    private final static int REQUEST_ALBUM = 0x02;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.editor)
    EditText editor;
    @Bind(R.id.image_grid)
    ImageGridView imageGrid;

    private Blog blog;//针对的商品
    private String blog_id;//日志发布成功后返回的id
    private User user;
    private YjnhImageWay imageWay;
    private Integer orderby = 0;//上传图片的排序
    private ArrayList<String> compressPaths;//压缩图片的路径，用于最后删除
    private ArrayList<ImgItemsBean> mImages = new ArrayList<>();//图片
    private AddImageAdapter mImgAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_release_journal);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        imageWay = new YjnhImageWay(mContext, REQUEST_ALBUM, REQUEST_CAMERA) {
            @Override
            public void album() {
                // 注意：若不重写该方法则使用系统相册选取(对应的onActivityResult中的处理方法也应不同)
                Intent it = new Intent(mContext, AlbumActivity.class);
                int size = mImages.size();
                it.putExtra("limitCount", 4 - size);// 图片选择张数限制
                it.putExtra("model", 1);// 图片是单选还是多选
                startActivityForResult(it, albumRequestCode);
            }
        };
        refreshImages();
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        blog = (Blog) mIntent.getSerializableExtra("blog");
    }

    @Override
    protected void setListener() {
        titleText.setText("发布");
        titleRightBtn.setText("保存");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
                showProgressDialog("请稍后");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
            case FILE_UPLOAD:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                HemaArrayResult<String> sResult = (HemaArrayResult<String>) baseResult;
                blog_id = sResult.getObjects().get(0);
                if (mImages.size() > 0) {
                    fileUpload();
                } else {
                    showTextDialog("发布成功！");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                }
                break;
            case FILE_UPLOAD:
                mImages.remove(0);
                if (mImages.size() > 0) {
                    fileUpload();
                } else {
                    showTextDialog("发布成功！");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1000);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                showTextDialog("发布失败！");
                break;
            case FILE_UPLOAD:
                showTextDialog("图片上传失败");
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_ADD:
                showTextDialog("发布失败！");
                break;
            case FILE_UPLOAD:
                showTextDialog("图片上传失败");
                break;
            default:
                break;
        }
    }

    /**
     * 上传多张照片
     */
    private void fileUpload() {
        String token = getApplicationContext().getUser().getToken();
        String imagePath = mImages.get(0).getImgurl();
        getNetWorker().fileUpload(token, "2", blog_id,
                "0", orderby + "", "无", imagePath);
        orderby++;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ALBUM:// 相册选择图片
                album(data);
                break;
            case REQUEST_CAMERA:// 拍照
                camera();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                String content = editor.getText().toString().trim();
                if (isNull(content)) {
                    XtomToastUtil.showShortToast(mContext, "请输入内容");
                    break;
                }
                getNetWorker().blogAdd(user.getToken(),
                        "3", "无", "无", "无", "无", "无", "无", "无", "无", "无", content, blog.getId(), "无", "无");
                break;
        }
    }

    /**
     * 显示图片选择对话
     */
    public void showPic() {
        new ActionSheetDialog(mContext)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (BaseUtil.checkCameraPermission(mContext)) {
                                    if (mImages.size() < 4)
                                        imageWay.camera();
                                    else
                                        XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                                }else {
                                    XtomToastUtil.showShortToast(mContext, "请打开相机权限");
                                    return;
                                }
                            }
                        })
                .addSheetItem("从相册打开", SheetItemColor.Black,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (mImages.size() < 4)
                                    imageWay.album();
                                else
                                    XtomToastUtil.showShortToast(mContext, "最多只能添加4张图片");
                            }
                        })
                .show();
    }

    private void camera() {
        String imagepath = imageWay.getCameraImage();
        new CompressPicTask().execute(imagepath);
    }

    private void album(Intent data) {
        if (data == null)
            return;
        ArrayList<String> imgList = data.getStringArrayListExtra("images");
        if (imgList == null)
            return;
        for (String img : imgList) {
            log_i(img);
            if (mImages.size() < 4) {
                new CompressPicTask().execute(img);
            }
        }
    }

    /**
     * 压缩图片
     */
    private class CompressPicTask extends AsyncTask<String, Void, Integer> {
        String compressPath;

        @Override
        protected Integer doInBackground(String... params) {
            try {
                String path = params[0];
                String savedir = XtomFileUtil.getTempFileDir(mContext);
                compressPath = XtomImageUtil.compressPictureWithSaveDir(path,
                        BaseConfig.IMAGE_HEIGHT, BaseConfig.IMAGE_WIDTH,
                        BaseConfig.IMAGE_QUALITY, savedir, mContext);
                return 0;
            } catch (Exception e) {
                return 1;
            }
        }

        @Override
        protected void onPreExecute() {
            showProgressDialog("请稍后");
        }

        @Override
        protected void onPostExecute(Integer result) {
            cancelProgressDialog();
            switch (result) {
                case 0:
                    if (compressPaths == null)
                        compressPaths = new ArrayList<>();
                    compressPaths.add(compressPath);

                    ImgItemsBean imageitem = new ImgItemsBean();
                    imageitem.setImgurl(compressPath);
                    imageitem.setImgurlbig(compressPath);
                    mImages.add(imageitem);
                    refreshImages();
                    break;
                case 1:
                    showTextDialog("图片压缩失败");
                    break;
            }
        }
    }

    /**
     * 刷新图片
     */
    private void refreshImages() {
        if (mImgAdapter == null) {
            mImgAdapter = new AddImageAdapter(mContext, mImages);
            mImgAdapter.setShowDelete(true);
            mImgAdapter.setShowAdd(true);
            imageGrid.setAdapter(mImgAdapter);
            mImgAdapter.setImageClickListener(new AddImageAdapter.OnImageClickListener() {
                @Override
                public void onImageClickListener(int position) {
                    if (mImages.size() < 4 && position == mImages.size()) {
                        showPic();
                    }else {
                        ArrayList<Img> imgs = new ArrayList<Img>();
                        for (int i = 0; i < mImages.size(); i++) {
                            ImgItemsBean item = mImages.get(i);
                            String imgurl_detail = item.getImgurlbig();
                            Img img = new Img(imgurl_detail);
                            imgs.add(img);
                        }

                        Intent intent = new Intent();
                        intent.setClass(mContext, ShowLargeImageActivity.class);
                        intent.putExtra("imgs", imgs);
                        intent.putExtra("position", position + 1);
                        mContext.startActivity(intent);
                    }
                }

                @Override
                public void onDeleteClickListener(int position, ImgItemsBean imageItem) {
                    mImages.remove(position);
                    mImgAdapter.notifyDataSetChanged();
                }
            });
        } else {
            mImgAdapter.notifyDataSetChanged();
        }
    }
}
